


import BaseClient from './baseClient';
import dyAdUtils from './dyAdUtils';

/**
 * 抖音/头条 分享视频逻辑:
 *
 * 1. 游戏开始 开始录制. 游戏界面是否显示录制中icon????
 * 2. 游戏暂停时 暂停录制, 游戏恢复时 继续录制
 * 3. 游戏在暂停界面退出的时候  需要中止录制
 * 4. 游戏过关或者失败的时候,中止录制
 * 5. 游戏过关的时候,点击分享 才可以分享视频
 * 6. 录制的时间必须 >=3 s
 *
 *  @extends BasicClient
 */
class ByteDance extends BaseClient{
    constructor(config){
        super();
        this.byteDance = (cc.sys.platform === cc.sys.BYTEDANCE_GAME);
        if(!this.byteDance){
            throw new Error('当前不是抖音平台.....');
        }

        dyAdUtils.init(config.bannerAdId,config.intersisterAdId,config.videoAdId);

        this.clipIndexList = [];

        this._updateVersion();

        this.reset();

        this.sysInfo = tt.getSystemInfoSync();
    }

    init(){

        tt.showShareMenu({
            withShareTicket:true,
            success:function () {
                console.log('showShareMenu success!');
            }
        });

        // 内存
        if(tt.onMemoryWarning){
            tt.onMemoryWarning(function () {
                tt.triggerGC();
            });
        }
    }

    reset(){
        this.videoPath = '';
        this.bReady = false;
        this.iStartTime = Date.now();
        this.videoTimeMs = 0; // 视频时长.
    }

    // 登陆错误回调
    onLoginError(){
        if(window.tt && tt.showModal){
            tt.showModal({
                title: '提示',
                content: '获取玩家信息失败',
                showCancel: false,
                confirmText: '确定',
            });
        }
    }

    // 版本更新
    _updateVersion(){
        const updateManager = tt.getUpdateManager();
        updateManager.onCheckForUpdate(function (res) {  // eslint-disable-line
            // console.log(res.hasUpdate)
        });
        updateManager.onUpdateReady(function () {
            updateManager.applyUpdate();
        });
        updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
        });
    }

    //-------------------------------------------
    startGameRecord(){
        if(this.isDevTools()){
            return;
        }
        if(!tt.getGameRecorderManager){
            return;
        }

        let recorder = tt.getGameRecorderManager();

        let self = this;
        recorder.onStop((res) => {
            recorder.clipVideo({
                path: res.videoPath,
                success:function(r) {
                    console.log(r.videoPath);
                    self.videoPath = r.videoPath;
                    let time = Date.now() - self.iStartTime;
                    self.videoTimeMs = time;
                    self.bReady = true;
                },
            });
        });

        recorder.start({
            duration:300,
            isMarkOpen:true, // 水印
            locTop:-200,
            locLeft:0,
        });
        this.reset();
    }

    recordClip(){
        if(this.isDevTools()){
            return;
        }
        if(!tt.getGameRecorderManager){
            return;
        }

        let self = this;
        let recorder = tt.getGameRecorderManager();
        recorder.recordClip({
            timeRange: [2, 2],
            success(r) {
                console.log(r.index); // 裁剪唯一索引
                self.clipIndexList.push(r.index);
            },
        });
    }

    stopGameRecord(){
        if(this.isDevTools()){
            return;
        }
        if(!tt.getGameRecorderManager){
            return;
        }

        const recorder = tt.getGameRecorderManager();
        recorder.stop();
    }
    pauseGameRecord(){
        if(this.isDevTools()){
            return;
        }
        if(!tt.getGameRecorderManager){
            return;
        }
        const recorder = tt.getGameRecorderManager();
        recorder.pause();
    }
    resumeGameRecord(){
        if(this.isDevTools()){
            return;
        }
        if(!tt.getGameRecorderManager){
            return;
        }
        const recorder = tt.getGameRecorderManager();
        recorder.resume();
    }
    shareVideo(successcb,failcb){

        if(this.isDevTools()){
            return;
        }

        if(!this.bReady){
            console.log('video 还没有准备好!');
            return;
        }

        // 小于3秒不可以分享
        if(this.videoTimeMs < 3000){
            console.log('视频时间过短!');
            return;
        }

        console.log('=========开始分享视频===');
        tt.shareAppMessage({
            channel:"video",
            templateId:'4k65p0f75hb1jtbdas',
            title:'这小游戏还挺有意思,点击就能玩',
            desc: "连击消除爽歪歪",
            query:'',
            extra: {
                // video_title:'精彩操作1111',
                videoPath: this.videoPath,
                hashtag_list:['祖玛来了'],
                videoTopics:['祖玛来了'],
            },
            success(res) {
                console.log('res:',res);
                console.log("分享视频成功");
                // 分享视频成功回调
                if(successcb){
                    successcb();
                }
            },
            fail(e) {
                console.log("分享视频失败. e:",e);
                if(failcb){
                    failcb();
                }
            },
        });
    }
    isDevTools(){
        return this.sysInfo.platform === 'devtools';
    }

    playVideoOrShare(opValue,obj){
        // 抖音下不进行分享
        this._showVideoAd(obj.success);
    }

    //-------------
    // ad 相关
    _showVideoAd(videoCb){
        if(dyAdUtils.VideoAdUtils.videoCachedSuccess()){
            dyAdUtils.VideoAdUtils.showVideoAd(videoCb);
        }else{
            window.ShSdk.getVideoFailTip('获取广告失败,请稍后重试!');
        }
    }

    cacheVideo(){
        dyAdUtils.VideoAdUtils.cacheVideoAd();
    }

    showBannerAd(){
        dyAdUtils.BannerAdUtils.showBannerAd();
    }

    hideBannerAd(){
        dyAdUtils.BannerAdUtils.hideBanner();
    }

    showInterAd(){
        dyAdUtils.InterstitialAdUtils.showInterstialAd();
    }
}


export default ByteDance;
